package com.rzico.sbl.ui.statistic

import android.view.inputmethod.EditorInfo
import android.widget.ImageView
import androidx.core.view.isGone
import androidx.core.view.isVisible
import androidx.core.widget.doOnTextChanged
import com.rzico.sbl.R
import com.rzico.sbl.databinding.ActivityTicketBinding
import com.rzico.sbl.model.TicketBarrelData
import com.rzico.sbl.other.*
import com.xinnuo.common.decoration.SpaceTBDecoration
import com.rzico.sbl.viewmodel.StatisticCommonViewModel
import com.xinnuo.common.extend.*
import com.xinnuo.common.helper.hideSoftInput
import com.xinnuo.common_ui.base.*
import com.xinnuo.common_ui.glideExt.loadImage
import com.xinnuo.common_ui.utils.showTimeRangeDialog
import com.xinnuo.slimadapter.SlimAdapter

class TicketActivity : BaseActivity(R.layout.activity_ticket) {

    private val mBinding by lazy { ActivityTicketBinding.bind(getRootView()) }

    private var mKeyWord = ""
    private var mDateMode = "4"
    private var mBeginDate = getFirstDate()
    private var mEndDate = getEndDate()

    override fun getViewModel() = get<StatisticCommonViewModel>()

    override fun initData() {
        setToolbarVisibility(false)

        initLayout()
        initSearch()

        mBinding
            .listLayout
            .swipeRefresh
            .isRefreshing = true

        getData(pageNum)
    }

    private fun initLayout() {
        mBinding.listLayout.apply {
            emptyLayout.also {
                it.emptyHint.text = "暂无相关水票信息！"
            }

            recycleList.also { view ->
                view.loadLinear(
                    refresh = swipeRefresh,
                    onRefresh = { getData(0) },
                    onLoad = {
                        isLoadingMore
                            .conditionFalse {
                                isLoadingMore = true
                                getData(pageNum)
                            }
                    }
                )

                view.addItemDecoration(SpaceTBDecoration(hasHeader = false))

                mAdapter = SlimAdapter.creator()
                    .register<TicketBarrelData>(R.layout.item_statistic_ticket) { jector, bean, _ ->
                        jector.apply {
                            text(R.id.item_ticket_name, bean.name)
                            text(R.id.item_ticket_num, bean.balance)
                            text(R.id.item_ticket_give, bean.gift.orEmpty("0"))
                            text(R.id.item_ticket_use, bean.used.orEmpty("0"))
                            text(R.id.item_ticket_sell, bean.pay.orEmpty("0"))

                            with<ImageView>(R.id.item_ticket_img) {
                                it.loadImage(bean.thumbnail)
                            }

                            clicked(R.id.item_ticket_give_ll) {
                                startActivityEx<TicketGiveActivity>(
                                    "goodsId" to bean.goodsId,
                                    "dateMode" to mDateMode,
                                    "beginDate" to mBeginDate,
                                    "endDate" to mEndDate
                                )
                            }

                            clicked(R.id.item_ticket_use_ll) {
                                startActivityEx<TicketUseActivity>(
                                    "goodsId" to bean.goodsId,
                                    "dateMode" to mDateMode,
                                    "beginDate" to mBeginDate,
                                    "endDate" to mEndDate
                                )
                            }

                            clicked(R.id.item_ticket_sell_ll) {
                                startActivityEx<TicketSellActivity>(
                                    "goodsId" to bean.goodsId,
                                    "dateMode" to mDateMode,
                                    "beginDate" to mBeginDate,
                                    "endDate" to mEndDate
                                )
                            }

                            clicked {
                                startActivityEx<TicketRecordActivity>(
                                    "goodsId" to bean.goodsId,
                                    "goodsName" to bean.name
                                )
                            }
                        }
                    }
                    .attachTo(view)
            }
        }
    }

    private fun initSearch() {
        mBinding
            .ticketSearch
            .apply {
                searchEdit.doOnTextChanged { text, _, _, _ ->
                    text?.let {
                        searchClose.isGone = it.isEmpty()

                        if (it.isEmpty() && mKeyWord.isNotEmpty()) {
                            mKeyWord = ""
                            updateList()
                        }
                    }
                }

                searchEdit.setOnEditorActionListener { _, actionId, _ ->
                    if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                        hideSoftInput() //隐藏软键盘

                        if (searchEdit.text.isBlank()) {
                            showToast("请输入关键字")
                        } else {
                            mKeyWord = searchEdit.textTrim
                            updateList()
                        }
                    }
                    return@setOnEditorActionListener false
                }

                searchClose.oneClick { searchEdit.setText("") }
                searchHint.oneClick {
                    if (searchEdit.text.isBlank()) {
                        showToast("请输入关键字")
                    } else {
                        mKeyWord = searchEdit.textTrim
                        updateList()
                    }
                }
            }
    }

    override fun initListener() {
        mBinding
            .ticketTime
            .apply {
                getViewModel().mUncheckTimeList[3].isChecked = true
                timeHint.text = getViewModel().mUncheckTimeList[3].hint

                timeLayout.oneClick {
                    getViewModel()
                        .showDropTimeFilter(
                            getIContext(),
                            timeHint,
                            timeHintArrow,
                            timeLayout,
                            getViewModel().mUncheckTimeList
                        ) { bean ->

                            if (bean.id != "7")
                                getViewModel()
                                    .mUncheckTimeList
                                    .last()
                                    .name = "自定义时间"

                            when (bean.id) {
                                "1" -> {
                                    mDateMode = "1"
                                    mBeginDate = getTodayDate()
                                    mEndDate = getTodayDate()

                                    updateList()
                                }
                                "2" -> {
                                    mDateMode = "2"
                                    mBeginDate = getBeforeDate()
                                    mEndDate = getBeforeDate()

                                    updateList()
                                }
                                "3" -> {
                                    mDateMode = "3"
                                    mBeginDate = getMondayDate()
                                    mEndDate = getSundayDate()

                                    updateList()
                                }
                                "4" -> {
                                    mDateMode = "4"
                                    mBeginDate = getFirstDate()
                                    mEndDate = getEndDate()

                                    updateList()
                                }
                                "5" -> {
                                    mDateMode = "5"
                                    mBeginDate = getBeforeFirstDate()
                                    mEndDate = getBeforeEndDate()

                                    updateList()
                                }
                                "6" -> {
                                    mDateMode = "6"
                                    mBeginDate = getYearFirstDate()
                                    mEndDate = getYearEndDate()

                                    updateList()
                                }
                                "7" -> {
                                    showTimeRangeDialog(
                                        isCurrentDate = true,
                                        isAfterLimited = true,
                                        onResult = { start, end ->
                                            getViewModel()
                                                .mUncheckTimeList
                                                .forEach { it.isChecked = false }

                                            getViewModel()
                                                .mUncheckTimeList
                                                .last()
                                                .isChecked = true

                                            mDateMode = "7"
                                            mBeginDate = start
                                            mEndDate = end
                                            bean.name = "$mBeginDate ~ $mEndDate"
                                            timeHint.text = bean.name

                                            updateList()
                                        }
                                    )
                                }
                            }
                        }
                }
            }
    }

    /**
     * 水票统计一级列表
     */
    override fun getData(index: Int, isLoading: Boolean) {
        getViewModel()
            .ticketList(
                page = index,
                keyWord = mKeyWord,
                beginDate = mBeginDate,
                endDate = mEndDate,
                onSuccess = {
                    mList.apply {
                        (index == 0)
                            .condition {
                                clear()
                                pageNum = 0
                            }

                        addItems(it.data)
                        it.data.notEmpty { pageNum++ }

                        mBinding.apply {
                            ticketGive.text = it.summary?.gift.orEmpty("0")
                            ticketUse.text = it.summary?.used.orEmpty("0")
                            ticketSell.text = it.summary?.pay.orEmpty("0")
                            ticketTotal.text = it.summary?.balance.orEmpty("0")
                        }
                    }

                    mAdapter.setDataList(mList)
                }
            ) {
                isLoadingMore = false

                mBinding
                    .listLayout
                    .apply {
                        swipeRefresh.isRefreshing = false

                        emptyLayout
                            .emptyView
                            .isVisible = mList.isEmpty()
                    }
            }
    }

    /**
     * 刷新列表数据
     */
    private fun updateList() {
        mBinding
            .listLayout
            .apply {
                swipeRefresh.isRefreshing = true

                emptyLayout
                    .emptyView
                    .gone()
            }

        mList.notEmpty {
            mList.clear()
            mAdapter.notifyDataSetChanged()
        }

        getData(0)
    }

}